package com.jffccloud.auth.security;

import com.jffccloud.auth.model.SysUser;
import com.jffccloud.auth.service.UserService;
import com.jffccloud.common.model.SecurityUser;
import com.jffccloud.common.util.HmacCode;
import com.jffccloud.common.util.PBKDF2Encryption;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.Collection;

@Component
@Slf4j
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserService userService;
    private final String key = "d80163ff92f3449ca72aada0c323afdc3daa2a8c7df33427a9a0010324edbc53";
    /**
     * 自定义验证方式
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        SysUser user = userService.findUserByUsername(username);
        if (user == null) {
            throw new BadCredentialsException("Username not found.");
        }

        byte[] btye = new byte[0];
        try {
            String salt = PBKDF2Encryption.generateSalt("http://www.xmjunxikeji.com");
            String ciphertext = PBKDF2Encryption.getEncryptedPassword(password, salt);
            Long createDatetime = user.getCreateTime().getTime()/1000;
            String pwd = ciphertext + createDatetime;
            btye = HmacCode.encodeHmacSHA256(pwd.getBytes(), key.getBytes());
        } catch (Exception e) {
           log.error("加密出错！"+e.getMessage(),e);
        }
        BigInteger bigInteger = new BigInteger(1, btye);
        password = bigInteger.toString(16);
        if (!password.equals(user.getPassword())) {
            throw new BadCredentialsException("Wrong password.");
        }
        Collection<GrantedAuthority> authorities = userService.loadUserAuthorities(user.getUserId());
        SecurityUser u = new SecurityUser(user.getUserId(),user.getUsername(),user.getPassword(),user.getName(),true,authorities);
        return new UsernamePasswordAuthenticationToken(u, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}